package com.linkhub.oms.component.excel.converter;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * LocalDateConverter
 *
 * @author Frank
 */
@Slf4j
public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);

    @Override
    public Class<LocalDateTime> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {

        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            Date date = HSSFDateUtil.getJavaDate(Double.parseDouble(StrUtil.toString(cellData.getNumberValue())));
            return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        } else if (cellData.getType() == CellDataTypeEnum.STRING) {
            String cellValue = cellData.getStringValue();
            if (StringUtils.isBlank(cellValue)) {
                log.warn("【{}】日期数据为空", cellValue);
                return null;
            }
            cellValue = cellValue.replace("/", "-");
            LocalDateTime localDate;
            try {
                //统一转换为 yyyy-MM-dd
                String[] strings = cellValue.split("-");
                cellValue = strings[0] + "-" + StrUtil.fillBefore(strings[1], '0', 2) + "-" + StrUtil.fillBefore(strings[2], '0', 2);
                localDate = LocalDateTime.parse(cellValue, FORMATTER);
            } catch (Exception e) {
                log.warn("【{}】不符合日期转换规则", cellValue);
                return null;
            }
            return localDate;
        } else {
            log.warn("第【{}】行【{}】列不符合日期转换", cellData.getRowIndex(), cellData.getColumnIndex());
            return null;
        }
    }


}
